<template>
    <el-select v-model="sval" clearable placeholder="请选择角色" :style="{width}" @change="onChcange" :disabled="disabled">
        <el-option v-for="dt in lists" :key="dt.id" :value="dt.id" :label="dt.roleName" />
    </el-select>
</template>
<script setup>
import {ref,onMounted,watch,nextTick} from "vue"
import {getRoleList} from '@/api/system'

const props = defineProps({
    modelValue:'',
    width:{
        type:String,
        default:'100%'
    },
    disabled:{
        type:Boolean,
        default:false
    },
    keyName:'' // 返回的属性名对应的值
})
const emit = defineEmits(['update:modelValue','change'])
const sval = ref('')
const lists = ref('')

onMounted(()=>{ 
    getTableData()
    // lists.value = [
    //     {roleName:'农场主'},
    //     {roleName:'经理'},
    //     {roleName:'管理员'},
    //     {roleName:'农事工人'}
    // ]
    // sval.value = props.modelValue || '' // 设置默认选项
})

watch(()=>props.modelValue,(n,o)=>{
    sval.value = n
})

const getTableData = async () => {
  const res = await getRoleList({ page: 1, limit: 100})
  if (res.code == 0) {
    lists.value = res.data
    //console.log("GGGGG:",props)
    sval.value = props.modelValue || '' // 设置默认选项
  }
}

const onChcange = ()=>{
    if(props.keyName){
        const item = lists.value.find(ele =>ele.id == sval.value)
        emit('update:modelValue',item[props.keyName]) 
        emit('change',sval.value) 
    }else{
        emit('update:modelValue',sval.value) 
        emit('change',sval.value) 
    }   
    if(sval.value){
        emit('onChange',lists.value.find(ele =>ele.id == sval.value))
    }
}

</script>

<style scoped lang="scss">
</style>